<?php
namespace XtwsAdmin\Controller;
use Think\Controller;

class LinkController extends CommonController{

    // 链接列表
    public function index(){
        $link = M('link');
        $where = "";
        if ($_GET['keyword'] != '') {
            $where = "title like '%" . $_GET['keyword'] . "%'";
            $this->assign('keyword', $_GET['keyword']);// 赋值分页输出
        }
        $link_arr = $link->where($where)->order('id desc')->select();

        foreach($link_arr as $k => $v){
            $detection = $this->detection_link($v['url']);
            $link_arr[$k]['detection'] = $detection?$detection: "<span style='color: #ff0300'>异常<span>";
        }//end foreach

        $this->assign('list', $link_arr);// 赋值数据集
        $this->display();
//        dump($link_arr);
    }// end fun

    //  添加链接
    public function addLink(){
        $link = M('link');
        if (IS_POST) {
            $data = $_POST;
            $data['addtime'] = time();
            $res = $link->add($data);
            if ($res) {
                $this->success('提交成功', '/XtwsAdmin/Link/');
            } else {
                $this->error('提交失败');
            }// end if
        } else {
            $this->display();
        }// end if
    }//end fun add

    //  修改链接
    public function editlink(){
        $link = M('link');
        $id = intval(I('id'));
        if (IS_POST) {
            $data = $_POST;
            $res = $link->save($data);
            if ($res) {
                $this->success('提交成功', '/XtwsAdmin/Link/');
            } else {
                $this->error('提交失败');
            }// end if
        } else {
            $info = $link->where('id='.$id)->find();
            $this -> assign('info',$info);
            $this->display();
        }// end if
    }//end fun add

    // 删除链接
    public function del(){
        $id = intval(I('id'));
        if ($id) {
            $link = M('link');
            $res = $link->delete($id);
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('出错啦，请检查');
            }
        } else {
            $this->error('请先选择链接');
        }//end if

    }//end fun

    //友情链接检测
    public function detection_link($url){

        $link = file_get_contents($url);//获取链接网页内容
//            $link = file_get_contents("http://news.xiangtws.com/Wx/Village/country/");

        $preg="/<a[^<>]+href *\= *[\"']?(http\:\/\/[^ '\"]+)+\">(.*)<\/a>/i";//过滤正则

        preg_match_all($preg, $link, $body_links, PREG_SET_ORDER);//组成数组
        $detection = array();
        foreach($body_links as $bk => $bv){
            if(strstr($bv[1],"zixun.xiangtws.com") != ''){
                $detection ='URL：'.$bv[1]."<br/>内容：".$bv[2];
            }//end if
        }//end foreach
        return($detection);
    }//end fun

}// end class